package pl.edu.pw.tm.zestawfiltrow.algorytmy;

import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Collections;

public class Median extends Filter {
	private static String name = "Medianowy";
	private int maskSize = 1;
	
	
	@Override
	public BufferedImage run(BufferedImage img) {
		
		int rgb;
		ArrayList<Integer> redArray, blueArray, greenArray;
		int width = img.getWidth();
		int height = img.getHeight();
		int middle = (maskSize*maskSize+maskSize)*2;
		BufferedImage newImage = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
		int[][] px = getPixels(img);
		for (int i = 0; i < width; i++) {
			for (int j = 0; j < height; j++) {
				if(i <maskSize || j<maskSize || i >= width-maskSize || j >= height-maskSize){
					rgb = toRGB(0, 0, 0);
					newImage.setRGB(i, j, (int) rgb);
				} else {
					redArray = new ArrayList<>();
					greenArray = new ArrayList<>();
					blueArray = new ArrayList<>();
					for(int ii = i-maskSize; ii <= i+maskSize; ii++){
						for(int jj = j-maskSize; jj <= j+maskSize; jj++){							
							redArray.add(getRed(px[ii][jj]));
							blueArray.add(getBlue(px[ii][jj]));
							greenArray.add(getGreen(px[ii][jj]));
						}						
					}					
					Collections.sort(redArray);
					Collections.sort(blueArray);
					Collections.sort(greenArray);
					rgb = toRGB(redArray.get(middle), greenArray.get(middle), blueArray.get(middle));
					
					newImage.setRGB(i, j, rgb );
				}				
			}
		}
		return newImage;
	}

	public String getName() {
		return name;
	}
}